;(function ($, window, document, undefined) {
    var PageGrid = function (opt) {
        _this = this;
        this.$container = $('#' + opt.containerId);
        this.containerId = opt.containerId;//容器的ID
        //按钮点击事件处理函数集合
        this.btnHandlers = {
            onAdd: function () {
                _this.openAdd();
            },
            onView: function () {
                _this.openView();
            },
            onDelete: function () {
                _this.deleteData();
            },
            onEdit: function () {
                _this.openEdit();
            },
            onExport: function () {
                _this.onExport();
            },
            onExportCsv: function () {
                _this.onExportCsv();
            }
        };
        this.datagridOptions = {
            fit: true,
            pagination: true,
            idField: 'ID',
            striped: true,
            rownumbers: true,
            fitColumns: false,
            fixed: true,
            singleSelect: false,
            border: false,
            toolbar: "#" + _this.containerId + " .pagegrid-toolbar"
        };
        //datagrid列格式化函数集合
        this.colFormatters = {};
        //默认值
        this.defaults = {
            contextUrl: '',
            module: '',
            submodule: '',
            moduleName: '',
            instantSearch: true,
            useCommonApi: false,
            noPermissionBtn: false,
            pageGridTmplId: '',
            showFlip: false,
            htmlEncode:false,
            viewName: '',
            datagridAutoColumnWidth: false//列宽随内容自适应宽度，出现这个属性是为了兼容老项目
        };
        this.options = $.extend({}, this.defaults, opt);
        this.btnHandlers = $.extend({}, this.btnHandlers, opt.btnHandlers);
        this.colFormatters = $.extend({}, this.colFormatters, opt.colFormatters);
        this.datagridOptions = $.extend({}, this.datagridOptions, opt.datagridOptions);
        this.btnData = $.extend({}, this.btnData, opt.btnData);
        this.contextUrl = this.options.contextUrl;
        this.module = this.options.module;
        this.submodule = this.options.submodule;
        this.moduleName = this.options.moduleName;
        var modulePath = this.options.module + "/" + this.options.submodule;
        this.cfgApi = this.options.contextUrl + "/api/ebp/viewcfg/" + modulePath;
        if (this.options.useCommonApi) {
            this.dataApi = this.options.contextUrl + '/api/ebp/commonquery/' + modulePath + "/list";
            this.exportApi = this.options.contextUrl + '/api/ebp/commonquery/' + modulePath + "/export";//导出api
        } else {
            this.dataApi = this.options.contextUrl + "/api/" + modulePath + "/list";
            this.exportApi = this.options.contextUrl + "/api/" + modulePath + "/export";
        }
        this.btnApi = this.options.contextUrl + '/api/ebp/syspermission/getCurrentUserBtnList?moduleId=' + this.options.module + "_" + this.options.submodule;
        this.instantSearch = this.options.instantSearch;
        this.columnDefDict = {};
        this.$queryForm = {};
        this.$btnBar = {};
        this.$datagrid = {};

        // By ken
        this.onPageLoadSuccess = this.options.onPageLoadSuccess;

    };
    PageGrid.prototype.build = function () {
        var _this = this;

        //加载页面配置
        var loadCfg = function () {
            return $.ajax({
                url: _this.cfgApi,
                type: 'get',
                dataType: 'json'
            });
        };

        //加载按钮数据
        var loadBtnData = function () {
            return $.ajax({
                url: _this.btnApi,
                type: 'get',
                dataType: 'json'
            });
        };

        //解析查询区域
        var parseQueryForm = function () {
            _this.$queryForm = $($('#' + _this.options.pageGridTmplId).html());// _this.$container.find(".pagegrid-searchform");
            //解析查询区域字段控件
            var colEles = _this.$queryForm.find('.col');
            console.log(_this.options.viewName);
            colEles.each(function (ix) {
                var $col = $(this);
                var $widget = $col.find('.query:first');
                if ($widget.length === 0) {
                    return;
                }
                var columnDef;
                if ($widget.attr('data-name')) {
                    columnDef = _this.columnDefDict[$widget.attr('data-name').toUpperCase()];
                } else {
                    columnDef = _this.columnDefDict[$widget.attr('data-qfield').toUpperCase()];
                }

                var finalViewName = 'query';
                if (_this.options.viewName) {
                    finalViewName = _this.options.viewName + '.query';
                }
                //console.log(finalViewName);
                if (columnDef && columnDef.visible && columnDef.visible[finalViewName]) {
                    $col.prepend('<label>' + columnDef.title + '：</label>');
                    var $container = $('<div></div>');
                    $container.append($col.children());
                    $col.append($container);
                } else {
                    $col.remove();
                }
            })
            var $toolbar = $('<div class="pagegrid-toolbar"></div>');
            var $searchboxArea = $('<div class="searchbox-area"></div>');
            var $searchBtnContainer = $('<div class="searchbox-flip"></div>');

            //生成“查询”
            var $btnSearch = $('<a style="margin-right: 20px;">查询</a>');
            $btnSearch.bind("click", function () {
                //先跳转到第一页
                var $pager = _this.$datagrid.datagrid('getPager')
                pageNumber = 1;
                pageSize = $pager.pagination('options').pageSize;
                $pager.pagination('refresh', {
                    pageNumber: pageNumber,
                    pageSize: pageSize
                });
                _this.search();
            });
            $btnSearch.linkbutton({iconCls: 'icon-search'});
            $searchBtnContainer.append($btnSearch);
            //生成“重置”按钮
            var $btnReset = $('<a>重置</a>');
            $btnReset.bind("click", function () {
                _this.resetSearchForm(_this.options.afterResetSearchForm);
            });
            $btnReset.linkbutton({iconCls: 'icon-undo'});
            $searchBtnContainer.append($btnReset);

            _this.$queryForm.append($searchBtnContainer);
            ;
            _this.$queryForm.appendTo($searchboxArea);
            if (_this.options.showFlip) {
                var upName = "↑收起 ↑";
                var downName = "↓展开 ↓";
                var $flipBar = $('<div class="searchbox-flip-bar" style="text-align: right;cursor: hand;color: blue;">' + upName + '</div>');
                $flipBar.bind("click", function () {
                    _this.$queryForm.toggle();
                    if ($(this).html() === upName) {
                        $(this).html(downName);
                    } else {
                        $(this).html(upName);
                    }
                    _this.$datagrid.datagrid('resize');
                });
                $flipBar.appendTo($searchboxArea);
            }

            $searchboxArea.appendTo($toolbar);
            _this.$container.append($toolbar);
            $.parser.parse(_this.$queryForm);
            ehsure.jothuheim.BringBack.parse(_this.$queryForm);

        };
        //解析按钮区域
        var parseBtnBar = function () {
            if (_this.btnData.length <= 0) {
                return;
            }
            var $btnBar = _this.$container.find(".toolbar-btnBar");
            if ($btnBar.length == 0) {
                _this.$btnBar = $('<div class="toolbar-btnBar"></div>');
            }

            var btnList = '';
            $.each(_this.btnData, function (ix, item) {
                var eventName = '';
                if (item.eventName && item.eventName.indexOf('(') > 0) {
                    eventName = item.eventName.substr(0, item.eventName.indexOf('('));
                } else {
                    eventName = item.eventName;
                }
                var $btn = $('<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="' + item.iconCls + '" plain="true" >' + item.name + '</a>');
                $btn.bind('click', function (e) {
                    e.preventDefault();

                    if (_this.btnHandlers[eventName]) {
                        _this.btnHandlers[eventName].apply(this, [_this]);
                    } else {
                        console.log("no event handler");
                    }
                });
                _this.$btnBar.append($btn);
            });
            var $toobar = _this.$container.find('.pagegrid-toolbar');
            $toobar.append(_this.$btnBar);
            $.parser.parse(_this.$btnBar);
        };
        //解析grid区域
        var parseGrid = function () {
            _this.$datagrid = $("<table ></table>");
            _this.$container.append(_this.$datagrid);

            //构造列定义
            var colDef = _this.columnDefDict;
            if (colDef) {
                _this.datagridOptions.columns = [[]];
                if (!_this.options.hideCheckBox) {
                    _this.datagridOptions.columns[0].push({field: 'ck', checkbox: true});
                }
                for (var fieldName in colDef) {
                    if (!colDef.hasOwnProperty(fieldName)) {
                        continue;
                    }
                    var finalViewName = 'list';
                    if (_this.options.viewName) {
                        finalViewName = _this.options.viewName + '.list';
                    }

                    if (colDef[fieldName] && colDef[fieldName].visible && colDef[fieldName].visible[finalViewName]) {
                        var colProperty = {
                            field: fieldName,
                            title: colDef[fieldName].title
                        };
                        /**
                         * 如果要让datagrid的列宽随内容自适应，不能设置列宽
                         * fitColumns 设置为 true，则会自动扩大或缩小列的尺寸以适应网格的宽度并且防止水平滚动。
                         * 自动列宽并且要允许滚动条就需要 datagridAutoColumnWidth==true 且 fitColumns=false 的时候不设置宽度                         *
                         *
                         */
                        if (_this.options.datagridAutoColumnWidth && !_this.datagridOptions.fitColumns) {
                            //不设置width
                        } else {//设置默认宽度，兼容老项目
                            //不设置列宽 IE页面上加载会有效率问题，所以老项目都设置了默认宽度
                            colProperty.width = 100;
                            if (colProperty.title.indexOf('单号') >= 0) {
                                colProperty.width = 120;
                            } else if (fieldName.indexOf('FULLNAME') >= 0) {
                                colProperty.width = 140;
                            } else if (fieldName === 'NAME') {
                                colProperty.width = 180;
                            } else if (fieldName.indexOf('TIME') >= 0) {
                                colProperty.width = 120;
                            } else if (fieldName.indexOf('DATE') >= 0) {
                                if (colProperty.title.length < 6) {
                                    colProperty.width = 80;
                                }
                            } else if (fieldName.indexOf('QTY') >= 0 || fieldName.indexOf('TIMES') >= 0) {
                                if (colProperty.title.length < 6) {
                                    colProperty.width = 80;
                                }
                            }
                        }

                        if (colDef[fieldName] && colDef[fieldName].width && colDef[fieldName].width.list) {
                            colProperty.width = colDef[fieldName].width.list;
                        }

                        if (_this.colFormatters[fieldName]) {
                            colProperty.formatter = _this.colFormatters[fieldName];
                        }
                        _this.datagridOptions.columns[0].push(colProperty);
                    }
                }
            }
            _this.$datagrid.datagrid(_this.datagridOptions);
            var $pager = _this.$datagrid.datagrid('getPager');
            $pager.pagination({
                onSelectPage: function (pageNumber, pageSize) {
                    _this.search(pageNumber, pageSize);
                }
            });

            _this.listen('onLoadSuccess', function (data) {
                $(this).datagrid('getPanel').find('.datagrid-cell-rownumber').each(function (i, v) {
                    var currentRowNumber = parseInt($(v).html());
                    var currentPage = $pager.pagination('options').pageNumber || 1;
                    var currentPageSize = $pager.pagination('options').pageSize || 10;
                    $(v).html(currentRowNumber + (currentPage - 1) * currentPageSize);
                });
                // $(this).datagrid('loaded');
                //修复 表头过长，没有加载数据或者加载数据为空时，不显示滚动条，导致显示不全表头字段
                var dv2 = $(".datagrid-view2");
                dv2.children(".datagrid-body").append("<div style='width:" + dv2.find(".datagrid-header-row").eq(0).width() + "px;border:solid 0px;height:1px;'></div>");
            });

            _this.$datagrid.datagrid('options').view.onAfterRender = function (target) {
                //datgrid横向滚动条不能正常显示，fix
                _this.$datagrid.parents('.datagrid-view').find('.datagrid-body').css('overflow-x', 'auto');
            };
            //修复 表头过长，没有加载数据或者加载数据为空时，不显示滚动条，导致显示不全表头字段
            var dv2 = $(".datagrid-view2");
            dv2.children(".datagrid-body").append("<div style='width:" + dv2.find(".datagrid-header-row").eq(0).width() + "px;border:solid 0px;height:1px;'></div>");
        };
        var parse = function () {
            parseQueryForm();
            parseBtnBar();
            parseGrid();
            if (_this.options.afterParse) {
                _this.options.afterParse();
            }
            _this.$container.panel({fit: true});
            if (_this.instantSearch) {
                //使用定时调用才能使进度条正常显示
                setTimeout(function () {
                    _this.search();
                }, 0);
            }
        }
        //开始执行
        loadCfg().done(function (cfgRes) {
            _this.columnDefDict = cfgRes;
            if (!_this.options.noPermissionBtn) {
                loadBtnData().done(function (btnRes) {
                    _this.btnData = btnRes.data;
                    parse();
                })
            } else {
                parse();
            }
        })
        return this;
    };

    PageGrid.prototype.listen = function (eventName, handler) {
        var event = this.$datagrid.datagrid('options')[eventName];
        if (event) {
            this.$datagrid.datagrid('options')[eventName] = handler;
        } else {
            console.dir(this.$datagrid.datagrid('options'));
            console.error('eventName not existed', eventName);
        }
    };
    PageGrid.prototype.getQueryParams = function () {
        var qParams = [];
        $.each(this.$queryForm.find('.query'), function (i, v) {
            var $obj = $(v);
            var subPara = {};
            subPara.field = $obj.data('qfield');
            subPara.type = $obj.data('qtype') || 'STRING';
            subPara.operator = $obj.data('qoperator') || 'EQUAL';

            if ($obj.hasClass('combobox-f') || $obj.hasClass('combotree-f')) {
                if ($obj.combo('options')['multiple']) {
                    subPara.value = $obj.combo('getValues').join(',');
                } else {
                    subPara.value = $obj.combo('getValue');
                }
            } else if ($obj.hasClass('datebox-f') || $obj.hasClass('datetimebox-f')) {
                subPara.value = $obj.datebox('getValue');
            } else {
                subPara.value = $obj.val();
            }
            if (subPara.value === '') {
                return;
            }
            qParams.push(subPara);
        });
        return qParams;
    };

    PageGrid.prototype.search = function (pageNumber, pageSize) {
        var _this = this;
        if (!_this.$queryForm.form('validate')) {
            return;
        }
        if (_this.options.beforeSearch) {
            var r = _this.options.beforeSearch(_this);
            if (!r) {
                return;
            }
        }
        //查询数据
        _this.$datagrid.datagrid('clearSelections');
        _this.$datagrid.datagrid('loading');
        var $pager = _this.$datagrid.datagrid('getPager')
        pageNumber = pageNumber || 1;
        pageSize = pageSize || $pager.pagination('options').pageSize || 25;
        var getData = function () {
            return $.ajax({
                url: _this.dataApi,
                type: "POST",
                contentType: "application/json",
                data: $.toJSON({
                    page: pageNumber,
                    rows: pageSize,
                    conditionItems: _this.getQueryParams()
                })
            });
        };
        var htmlEncodeFun = function(res){
            $.each(res.rows,function(i,item){
                $.each(item,function (name,value) {
                    if(typeof value == "string"){
                        item[name] = value.replace(/&/g,"&amp;")
                            .replace(/"/g,"&quot;")
                            .replace(/'/g,"&apos;")
                            .replace(/</g,"&lt;")
                            .replace(/>/g,"&gt;");
                    }
                });
            });
        }
        getData().done(function (res) {
            if(_this.options.htmlEncode){
                htmlEncodeFun(res);
            }
            _this.$datagrid.datagrid('loadData', res);

            // By ken 判断页面加载后，执行自定义方法
            if (_this.onPageLoadSuccess) {
                _this.onPageLoadSuccess(res);
            }

        }).always(function () {
            _this.$datagrid.datagrid('loaded');
        });
    };

    PageGrid.prototype.resetSearchForm = function (afterReset) {
        this.$queryForm.form('reset');
        if (afterReset) {
            afterReset();
        }
    };
    PageGrid.prototype.getApiUrl = function (action) {
        return this.contextUrl + "/api/" + this.module + '/' + this.submodule + '/' + action;
    };
    PageGrid.prototype.getPageUrl = function (action, isCustom) {
        isCustom = isCustom || false;
        var viewPrefix = isCustom ? '/' : '/view/';
        return this.contextUrl + viewPrefix + '/' + this.module + '/' + this.submodule + '/' + action;
    };
    PageGrid.prototype.getCommonQueryUrl = function (action, id) {
        if (action === 'getbyid') {
            return this.baseUrl + '/api/ebp/commonquery/' + this.module + '/' + this.submodule + '/getbyid/' + id;
        } else {
            return this.baseUrl + '/api/ebp/commonquery/' + this.module + '/' + this.submodule + '/' + action;
        }
    };
    PageGrid.prototype.openWin = function (action, winTitle, queryStr, winType, winOptions) {
        winType = winType || 'tab';
        var url = this.getPageUrl(action);
        if (queryStr && queryStr.length > 0) {
            url += (url.indexOf('?') > 0 ? '&amp' : '?') + queryStr;
        }
        this.openOtherWin(url, winTitle, winType, winOptions);
    };
    PageGrid.prototype.openOtherWin = function (url, winTitle, winType, winOptions) {
        var _this = this;
        winType = winType || 'tab';
        switch (winType) {
            case 'tab':
                parent.addTab(winTitle, url);
                break;
            case 'dialog':
                var $dialog = $('<div></div>').appendTo($('body'));
                $dialog.dialog({
                    title: winTitle,
                    width: 700,
                    height: 500,
                    maximizable: true,
                    resizable: true,
                    cache: false,
                    href: url,
                    modal: true,
                    onClose: function () {
                        $(this).dialog('destroy');
                    }
                });
                _this.$dialog = $dialog;
                break;
            default:
                parent.addTab(winTitle, url);
                break;
        }
    };
    PageGrid.prototype.openAdd = function (queryStr, winOptions) {
        var _this = this;
        _this.openWin('add', "添加" + _this.moduleName, queryStr, winOptions);
    };
    /**
     * 打开查看页面
     * @param {string} [winType='type'] 要打开窗体的类型： tab|dialog 。默认为tab
     * @param {WinOptions} [winOptions] 要打开窗体的附加参数
     */
    PageGrid.prototype.openView = function (winType, winOptions) {
        this.openSelected('detail', "查看" + this.moduleName, winType, winOptions);
    };

    /**
     * 打开编辑页面
     * @param {string} [winType='type'] 要打开窗体的类型： tab|dialog 。默认为tab
     * @param {WinOptions} [winOptions] 要打开窗体的附加参数
     */
    PageGrid.prototype.openEdit = function (winType, winOptions) {
        this.openSelected('edit', "编辑" + this.moduleName, winType, winOptions);
    };

    PageGrid.prototype.getSingleSelected = function () {
        var rows = this.$datagrid.datagrid('getSelections');
        if (!rows || rows.length === 0) {
            $.messager.alert('警告', "请至少选中一行", "warning");
            return null;
        }
        if (rows.length > 1) {
            $.messager.alert('警告', "只能选中一行", "warning");
            return null;
        }
        return rows[0];
    };

    PageGrid.prototype.getMultiSelected = function () {
        return this.$datagrid.datagrid('getSelections');
    };

    PageGrid.prototype.openSelected = function (action, winTitle, winType, winOptions) {
        var row = this.getSingleSelected();
        if (!row) {
            return false;
        }
        var id = row.id || row.ID || row.Id;
        this.openWin(action, winTitle, "id=" + id, winType, winOptions);
        return true;
    };

    PageGrid.prototype.deleteData = function () {
        var _this = this;
        var rows = this.getMultiSelected();
        if (!rows || rows.length === 0) {
            $.messager.alert('警告', "请选择数据！", "warning");
            return;
        } else {
            $.messager.confirm('确认操作', '确认要删除吗？', function (r) {
                if (r) {
                    _this.doDelete(rows);
                }
            });
        }
    };

    PageGrid.prototype.doDelete = function (rows) {
        var ss = [];
        for (var i = 0; i < rows.length; i++) {
            var row = rows[i];
            ss.push({name: "ids", value: "" + (row.id || row.ID ) + ""});
        }
        var _this = this;
        $.messager.progress({text: ''});
        $.ajax({
            type: 'post',
            url: this.getApiUrl('delete'),
            data: ss
        }).done(function (data) {
            if (data.code === 0) {
                $.messager.alert('提示', '删除成功');
                _this.search();
            } else {
                $.messager.alert('删除失败', data.errMsg, 'warning');
            }
        }).always(function () {
            $.messager.progress('close');
        });
    };
    PageGrid.prototype.onExportCsv = function () {
        this.export('csv');
    }
    PageGrid.prototype.onExport = function () {
        this.export();
    }
    PageGrid.prototype.export = function (exportType) {
        var _this = this;
        var queryParams = _this.getQueryParams();

        var $form = $('<form method="post" action="" target="_blank"></form>');
        $form.attr('action', _this.exportApi);
        if (exportType) {
            var $inputPageExportType = $('<input name="pageExportType" value="' + exportType + '" type="hidden"/>');
        }

        var $inputPageReq = $('<input  name="pageReqStr" type="hidden"/>');
        var $inputPageDef = $('<input name="pageDefStr" type="hidden" />');
        var $inputPageTitle = $('<input  name="pageTitle" type="hidden" />');
        var columnArr = _.filter(_this.$datagrid.datagrid('options').columns[0].map(function (col) {
            return {name: col.field, title: col.title};
        }), function (col) {
            return col.name !== 'ck' && col.name !== 'ID';
        });
        $inputPageDef.val($.toJSON(columnArr));
        $inputPageReq.val($.toJSON({
            page: 1,
            rows: 1,
            conditionItems: queryParams
        }));
        $inputPageTitle.val(_this.options.moduleName);


        $form.append($inputPageReq);
        $form.append($inputPageDef);
        $form.append($inputPageTitle);
        $form.append($inputPageExportType);
        $('body').append($form);
        $form.submit();
        $form.remove();
    };

    PageGrid.formmater = (function () {
        var obj = {};

        obj.bool2Checkbox = function (value, row) {
            var $checkbox = $('<span><input type="checkbox" value="true" disabled /></span>');
            if (value) {
                $checkbox.find('input').attr('checked', 'checked');
            }
            return $checkbox.html();
        };

        return obj;
    })();

    ehsure = ehsure || {};
    ehsure.PageGrid = PageGrid;

})(jQuery, window, document);